package cn.edu.ujs.coor.service;

import cn.edu.ujs.coor.common.exception.CoorException;
import cn.edu.ujs.coor.common.oss.service.OssService;
import cn.edu.ujs.coor.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@Service
public class CommonService {

    @Autowired
    private OssService ossService;

    /**
     * 文件下载
     * @param file
     * @param response
     */
    public void download (String file, HttpServletResponse response) {
        if (StringUtils.isBlank(file)) {
            throw new CoorException("文件名非空");
        }
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file));
            ByteArrayOutputStream baos = ossService.get(file);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(baos.toByteArray());
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CoorException("文件下载失败");
        }
    }

    /**
     * 文件下载
     * @param exportName
     * @param response
     */
    public void download (List<String> files, HttpServletResponse response, String exportName) {
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(exportName));
            ByteArrayOutputStream baos = ossService.get(files);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(baos.toByteArray());
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CoorException("文件下载失败");
        }
    }

    /**
     * 文件上传
     * @param file
     */
    public String upload (MultipartFile file, User user) {
        return ossService.put(file, user);
    }
}
